<?php
/**
 * @description : authorized the request token
 * @author      : stephen.mo <stephen.mo@achievo.com>
 * @date        : 2010/07/16
 */
require_once "TVB/OAuth/common.inc.php";
#ini_set("display_errors","on");

//get OAuth Parameters
$req     = OAuthRequest::from_request();
$request = $req->get_parameters();

//setting the vars
$lang            = (isset($_REQUEST['lang'])) ? OAuthUtils::chkLang($_REQUEST['lang']) : OAuthConfig::DEFAULT_SUPPORT_LANG;
$login_self      = (isset($_REQUEST['login_self'])) ? $_REQUEST['login_self'] : OAuthConfig::OAuthGetRestUrl($_SERVER);
$oauth_token     = (isset($request['oauth_token'])) ? $request['oauth_token'] : ((isset($_REQUEST['oauth_token'])) ? $_REQUEST['oauth_token'] : NULL);
$oauth_callback  = (isset($request['oauth_callback'])) ? $request['oauth_callback'] : ((isset($_REQUEST['oauth_callback'])) ? $_REQUEST['oauth_callback']: NULL);
$oauth_reback    = (isset($request['oauth_reback'])) ? $request['oauth_reback'] : ((isset($_REQUEST['oauth_reback'])) ? $_REQUEST['oauth_reback'] : NULL);
$phone_imei      = (isset($request['oauth_imei'])) ? $request['oauth_imei'] : NULL;

//setting path.
$base_server_url = OAuthConfig::OAuthDomainUrl($_SERVER);
$reset_page_url  = OAuthConfig::OAuthGetRestUrl($_SERVER);
$default_header  = $base_server_url.OAuthConfig::DEFAULT_HEADER_URL;
$jqtouch_url     = $base_server_url.OAuthModelConfig::DEFAULT_MOBILE_TEMPLATE;
$forget_password = $base_server_url.OAuthConfig::MEMBER_FORGET_URL.'?lang='.$lang.'&reback_url='.urlencode($login_self);
$skip_url        = $default_header.'?oauth_reback='.$login_self;
$register_url    = $base_server_url.OAuthConfig::DEFAULT_REGISTER_URL.'?lang='.$lang;
$skip_reback     = (!empty($oauth_reback)) ? $oauth_reback : ((!empty($oauth_callback)) ? $oauth_callback : '#');
$reback_urls     = (!empty($oauth_reback)) ? '&reback_url='.$oauth_reback : NULL;
$join_reg_url    = $base_server_url.OAuthConfig::DEFAULT_CMODEL_URL.'?call_back='.urlencode($oauth_callback).$reback_urls.'&lang='.$lang;
$message_url     = $base_server_url.OAuthConfig::DEFAULT_SHOW_MESSAGE_URL;

//check member is logined with memcache.
if (OAuthModelConfig::USING_MEM_SAVE_MEMBER) {/*{{{*/

    $login_id   = (isset($request['oauth_username'])) ? $request['oauth_username'] : NULL;
    if (!empty($login_id)) {
        $userData   = OAuthUtils::checkUserState($login_id,$phone_imei);
        $login_token = $userData['token'];
        $ret = OAuthUtils::chkSSOLoginStatus($login_token,$login_id);
        if ($ret == 2 && $userData != FALSE) {
            //exists & get the info to rebuild token and switch it. 
            $rand_code     = (isset($userData['rand_code'])) ? $userData['rand_code'] : NULL;
            $request_token = (isset($userData['request_token'])) ? $userData['request_token'] : NULL;
            $username      = (isset($userData['user'])) ? $userData['user'] : NULL;
            if (!empty($rand_code) && !empty($request_token) && !empty($username)) {
                $ck_request_token  = $request_token;
                $ck_request_secret = $userData['request_secret'];
                $callback_url      = $oauth_callback;

                $tmp_request_token = OAuthUtils::checkTokenAuthorized($rand_code);
                if (!empty($ck_request_secret) && $ck_request_token==$tmp_request_token) {
                    $output = 'oauth_token='.$tmp_request_token.'&oauth_token_secret='.$ck_request_secret.'&oauth_verifier='.$rand_code;
                    if (empty($callback_url)) {
                        echo $output;
                        exit;
                    }
                    else {
                        $callback_url = (strpos($callback_url,'?')) ? $callback_url.'&'.$output : $callback_url.'?'.$output;
                        header("Location: $callback_url");
                        exit;
                    }
                }
            }
        }
    }

}/*}}}*/

//submit requestion and check the email & password is or not correct.
 if (isset($_REQUEST['submit_']) && $_REQUEST['submit_']) {/*{{{*/
    $now_time   = time();
    //check username & password is or not pass.
    $username   = (isset($_REQUEST['email'])) ? $_REQUEST['email'] : NULL;
    $password   = (isset($_REQUEST['password'])) ? $_REQUEST['password'] : NULL;
    $other_msg  = array('call_back'=>urlencode($login_self));

    //check username.
    if (empty($username)) {
        OAuthUtils::toMessageUrl($message_url,OAuthModelConfig::M_PAGE_OF_ERROR,OAuthModelConfig::DEFAULT_CONST_FALIURE,$lang,array(1001),$other_msg);
        exit;
    }
    //check password
    if (empty($password) || strlen($password) < 6) {
        OAuthUtils::toMessageUrl($message_url,OAuthModelConfig::M_PAGE_OF_ERROR,OAuthModelConfig::DEFAULT_CONST_FALIURE,$lang,array(1003),$other_msg);
        exit;
    }
    //check email address.
    if (!preg_match(OAuthModelConfig::DEFAULT_EMAIL_PREG_MATCH,$username)) {
        OAuthUtils::toMessageUrl($message_url,OAuthModelConfig::M_PAGE_OF_ERROR,OAuthModelConfig::DEFAULT_CONST_FALIURE,$lang,array(1002),$other_msg);
        exit;
    }
    //save the tmp username with remeber  
    if (OAuthModelConfig::USING_MEM_SAVE_MEMBER) {
        $params = array();
        $params['user'] = $username;
        $params['pass'] = $password;
        $params['remeber'] = 1;
        OAuthUtils::setUserInfo($params,OAuthModelConfig::SAVE_MEMBER_INFO_ETIME);
    }
    
    //TODO IT Login into TVB.COM
    $rev = OAuthUtils::loginForMobile($username,$password,NULL,TRUE);
    if (!is_object($rev) && $rev == -1) {
        OAuthUtils::toMessageUrl($message_url,OAuthModelConfig::M_PAGE_OF_ERROR,OAuthModelConfig::DEFAULT_CONST_FALIURE,$lang,array(1042),$other_msg);
        exit;
    }
    if (!$rev) {
        OAuthUtils::toMessageUrl($message_url,OAuthModelConfig::M_PAGE_OF_ERROR,OAuthModelConfig::DEFAULT_CONST_FALIURE,$lang,array(1004),$other_msg);
        exit;
    }
    //get this login's token. 
    $login_token = $rev->token;

    //authorized the request token and return the verify code.
    //check and authorize request token.
    $callback_url  = (isset($_REQUEST['oauth_callback']) && !empty($_REQUEST['oauth_callback'])) ? $_REQUEST['oauth_callback'] : NULL;
    $request_token = (isset($_REQUEST['request_token'])) ? $_REQUEST['request_token'] : NULL;
    $consumer_key  =  OAuthUtils::getConsumerKeyByToken($request_token);
    if (empty($consumer_key) || empty($request_token)) {
        OAuthUtils::toMessageUrl($message_url,OAuthModelConfig::M_PAGE_OF_ERROR,OAuthModelConfig::DEFAULT_CONST_FALIURE,$lang,array(1005),$other_msg);
        exit;
    }

    //authorize the request token and return authorized token.
    $request_vars = array();
    $request_vars['consumer_key']  = $consumer_key;
    $request_vars['request_token'] = $request_token;
    $request_vars['user_name']     = $username;
    $authorize_result = OAuthUtils::authorizedRequestToken($request_vars);
    if (!$authorize_result) {
        OAuthUtils::toMessageUrl($message_url,OAuthModelConfig::M_PAGE_OF_ERROR,OAuthModelConfig::DEFAULT_CONST_FALIURE,$lang,array(1006),$other_msg);
        exit;
    }

    //setting the cookie vars.
    $params = array();
    $params['rand_code']      = $authorize_result['oauth_verify'];
    $params['request_token']  = $request_token;
    $params['request_secret'] = $authorize_result['secret'];
    $params['user']           = $username;
    $params['login_id']       = OAuthUtils::getLoginIdByEmail($username);
    $params['token']          = $login_token;

    //if open the memcache server then saving it to mc.(user info and request parameters)
    if (OAuthModelConfig::USING_MEM_SAVE_MEMBER) {
        OAuthUtils::setRequest($params,OAuthModelConfig::SAVE_MEMBER_INFO_ETIME);
        OAuthUtils::setUserInfo($params,OAuthModelConfig::SAVE_MEMBER_INFO_ETIME);
    }
    
    //save data to mc.
    $rev = OAuthUtils::saveUserInfoToMc($params,OAuthModelConfig::SAVE_MEMBER_INFO_ETIME);
    $rev = OAuthUtils::saveLoginInfo($username,$lang);

    //return or output.
    $output = 'oauth_token='.$authorize_result['key'].
              '&oauth_token_secret='.$authorize_result['secret'].
              '&oauth_verifier='.$authorize_result['oauth_verify'];
    if (!empty($callback_url)) {
        $callback_url = (strpos($callback_url,'?')===false) ? $callback_url.'?'.$output : $callback_url.'&'.$output;
        Header("Location:$callback_url");
        exit;
    }
    
    //output the authorized token string.
    echo $output;
    exit;

}/*}}}*/

//set the remember me.
$tmp_user_name = NULL;
$tmp_user_pass = NULL;

//is open and using cookie??
if (OAuthConfig::USING_COOKIES) {
    $userInfo      = OAuthUtils::getUserInfo();
    $login_from    = (isset($userInfo['from'])) ? $userInfo['from'] : NULL;
    if (empty($login_from) || ($login_from != OAuthModelConfig::PCCW_OAUTH_FROM_TYPE)) {
        $tmp_user_name = $userInfo['user'];
        $tmp_user_pass = $userInfo['pass'];
    }
}

//page info vars
$login_page_info = OPI::$login_page_info;
$payment_buttons = OPI::$payment_button_info;
$language_info   = OPI::$language_info;

//third parties login
$thirdlogin = array();
if (OAuthModelConfig::OAUTH_OPEN_THIRD_PARTY_LOGIN && OAuthUtils::chkIsExistsThirdPartyLogin()) {
    $oauth_callback    = (empty($oauth_callback)) ? $reset_page_url : $oauth_callback; 
    $oauth_token_str   = (!empty($oauth_token)) ? '&oauth_token='.$oauth_token : NULL;
    $third_parties_url = $base_server_url.OAuthConfig::DEFAULT_THIRD_PARTIES_URL.'?oauth_callback='.urlencode($oauth_callback).
                         '&lang='.$lang.$oauth_token_str;
    $thirdlogin['href'] = $third_parties_url;
    $thirdlogin['name'] = $login_page_info[$lang]['third_parties'];
}


//setting the form datas into array.
$form = array();
$using_real_env                     = OAuthModelConfig::USING_TEMPLATE_ON_REAL_ENV;
$page                               = OAuthModelConfig::M_PAGE_OF_LOGIN;
$form['lang']                       = $lang;
$form['title']                      = $login_page_info[$lang]['page_title'];
$form['action']                     = 'authorize.php';
$form['method']                     = 'POST';
$form['login_title']                = $login_page_info[$lang]['login_title'];
$form['login_note']                 = $login_page_info[$lang]['page_title'];
//hidden input
$form['hidden']['request_token']    = $oauth_token;
$form['hidden']['submit_']          = 1;
$form['hidden']['oauth_callback']   = $oauth_callback;
$form['hidden']['login_self']       = $login_self;
$form['email']['title']             = $login_page_info[$lang]['login_id'];
$form['email']['value']             = $tmp_user_name;
$form['email']['note']              = NULL;
$form['pass']['title']              = $login_page_info[$lang]['password'];
$form['pass']['value']              = $tmp_user_pass;
//buttons setting.
$form['button']['signin']['value']  = $payment_buttons[$lang]['login'];
$form['button']['cancel']['value']  = $payment_buttons[$lang]['back'];
$form['button']['cancel']['link']   = $skip_url;
//links setting.
$form['link']['forget']['href']     = $forget_password;
$form['link']['forget']['name']     = (isset($login_page_info[$lang]['forget'])) ? $login_page_info[$lang]['forget'] : NULL;
$form['link']['register']           = (isset($login_page_info[$lang]['login_reg'])) ? $login_page_info[$lang]['login_reg'] : NULL;
$form['link']['register']['href']   = $register_url;
$form['link']['thirdlogin']['href'] = (isset($thirdlogin['href'])) ? $thirdlogin['href'] : NULL;
$form['link']['thirdlogin']['name'] = (isset($thirdlogin['name'])) ? $thirdlogin['name'] : NULL;
$form['link']['joins']              = (isset($login_page_info[$lang]['login_joins'])) ? $login_page_info[$lang]['login_joins'] : NULL;
$form['link']['joins']['href']      = $join_reg_url;

//include the template for login
include "..".OAuthModelConfig::DEFAULT_MOBILE_TEMPLATE.OAuthModelConfig::$mobile_teplate_page[$page];

?>
